<?php


namespace LazadaApi\Services;


use GuzzleHttp\Client;
use function GuzzleHttp\Psr7\parse_query;

class LazadaLoginService
{
    const COUNTRY_SG = 'sg';
    const COUNTRY_MY = 'my';
    const COUNTRY_TH = 'th';
    const COUNTRY_VN = 'vn';
    const COUNTRY_PH = 'ph';
    const COUNTRY_ID = 'id';
    const COUNTRY_CB = 'cb';
    private $_accessTokenService;

    public function __construct(LazadaAccessTokenService $accessTokenService)
    {
        $this->_accessTokenService = $accessTokenService;
    }

    /**
     * @param string $account
     * @param string $password
     * @param string $country cb 国家：sg(新加坡),my(马来西亚),th(泰国),vn(越南),ph(菲律宾),id(印度),cb(一次性授权前面6国店铺)
     *
     * @return mixed
     * @throws \Exception
     */
    public function login(string $account, string $password, string $country = self::COUNTRY_CB)
    {
        $code = $this->_getAuthCode($country, $account, $password);

        return $this->_accessTokenService->generate($code);
    }

    private function _getAuthCode(string $country, string $account, string $password): string
    {
        $config = [
            'base_uri' => 'https://uac.lazada.com',
            'timeout'  => 10.0,
            'cookies'  => true,
        ];

        $httpClient   = new Client($config);
        $account      = urlencode($account);
        $loginUrl     = "https://uac.lazada.com/seller/login?account={$account}&password={$password}&country={$country}&redirect_url=https%3A%2F%2Fauth.lazada.com%2Foauth%2Fauthorize%3Fresponse_type%3Dcode%26country%3D{$country}%26force_auth%3Dtrue%26client_id%3D113899%26redirect_auth%3Dtrue&from=lazop_auth&callback=__jp2";
        $response     = $httpClient->get($loginUrl);
        $appKey       = config('lazada.appKey');
        $redirectUrl  = "https://auth.lazada.com/oauth/authorize?response_type=code&country={$country}&force_auth=true&client_id={$appKey}&redirect_auth=true";
        $redirectResp = $httpClient->get($redirectUrl, [
            'allow_redirects' => false
        ]);
        $codeUrl      = $redirectResp->getHeader('Location');
        $queryArr     = parse_query($codeUrl[0]);
        $authCode     = array_pop($queryArr);

        return $authCode;
    }
}